package com.collect.senegal.zhiHelper;

import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiManager;
import android.util.Log;

import androidx.core.app.ActivityCompat;

import com.collect.senegal.MyApplication;
import com.collect.senegal.zhiAdater.zhiTestWifiList.ZHIWifiEntity;

import java.util.ArrayList;
import java.util.List;

/**
 * WiFi连接管理
 * 申请权限
 * <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
 * <uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/>
 * <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
 * <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
 * 动态权限
 * Manifest.permission.ACCESS_COARSE_LOCATION
 * Manifest.permission.ACCESS_FINE_LOCATION
 */
public class ZHIWifiConnectHelper {
    private static final String TAG = "ZHIWifiConnectHelper";
    private ArrayList<ZHIWifiEntity> mWifiList = new ArrayList<>();
    private static ZHIWifiConnectHelper utils = null;

    public ZHIWifiConnectHelper() {
        wifiManager = (WifiManager) MyApplication.getApp().getApplicationContext().getSystemService(Context.WIFI_SERVICE);
    }

    public static ZHIWifiConnectHelper getInstance(Context context) {
        if (utils == null) {
            synchronized (ZHIWifiConnectHelper.class) {
                if (utils == null) {
                    utils = new ZHIWifiConnectHelper();
                }
            }
        }
        return utils;
    }

    private WifiManager wifiManager;

    /**
     * wifi是否打开
     *
     * @return
     */
    public boolean isWifiEnable() {
        boolean isEnable = false;
        if (wifiManager != null) {
            if (wifiManager.isWifiEnabled()) {
                isEnable = true;
            }
        }
        return isEnable;
    }

    /**
     * 判断是否已连上公司wifi
     */
    public boolean isConnectCompanyWifi() {
        if (wifiManager != null && wifiManager.getConnectionInfo() != null) {
            String gssid = wifiManager.getConnectionInfo().getSSID();
            String gbssid = wifiManager.getConnectionInfo().getBSSID();

            Log.d(TAG, "isConnectCompanyWifi: " + wifiManager.getConnectionInfo().toString());

        }
        return false;
    }

    /**
     * 打开WiFi
     */
    public void openWifi() {
        if (wifiManager != null && !isWifiEnable()) {
            wifiManager.setWifiEnabled(true);
        }
    }

    /**
     * 关闭WiFi
     */
    public void closeWifi() {
        if (wifiManager != null && isWifiEnable()) {
            wifiManager.setWifiEnabled(false);
        }
    }

    /**
     * 获取WiFi列表
     *
     * @return
     */
    public List<ScanResult> getWifiList() {
        List<ScanResult> resultList = new ArrayList<>();
        if (wifiManager != null && isWifiEnable()) {
            resultList.addAll(wifiManager.getScanResults());
        }
        return resultList;
    }

    /**
     * 有密码连接
     *
     * @param ssid
     * @param pws
     */
    public void connectWifiPws(Context context, String ssid, String pws) {
        wifiManager.disableNetwork(wifiManager.getConnectionInfo().getNetworkId());
        int netId = wifiManager.addNetwork(getWifiConfig(context, ssid, pws, true));
        wifiManager.enableNetwork(netId, true);
    }

    /**
     * 无密码连接
     *
     * @param ssid
     */
    public void connectWifiNoPws(Context context, String ssid) {
        wifiManager.disableNetwork(wifiManager.getConnectionInfo().getNetworkId());
        int netId = wifiManager.addNetwork(getWifiConfig(context, ssid, "", false));
        wifiManager.enableNetwork(netId, true);
    }

    /**
     * wifi设置
     *
     * @param ssid
     * @param pws
     * @param isHasPws
     */
    private WifiConfiguration getWifiConfig(Context context, String ssid, String pws, boolean isHasPws) {
        WifiConfiguration config = new WifiConfiguration();
        config.allowedAuthAlgorithms.clear();
        config.allowedGroupCiphers.clear();
        config.allowedKeyManagement.clear();
        config.allowedPairwiseCiphers.clear();
        config.allowedProtocols.clear();
        config.SSID = "\"" + ssid + "\"";

        WifiConfiguration tempConfig = isExist(context, ssid);
        if (tempConfig != null) {
            wifiManager.removeNetwork(tempConfig.networkId);
        }
        if (isHasPws) {
            config.preSharedKey = "\"" + pws + "\"";
//            config.hiddenSSID = true;

            config.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
            config.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
            config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
            config.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
            config.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
            config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
            config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP104);
            config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
            config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
            config.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);
            config.status = WifiConfiguration.Status.ENABLED;
        } else {
            config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
        }
        return config;
    }

    /**
     * 得到配置好的网络连接
     *
     * @param ssid
     * @return
     */
    private WifiConfiguration isExist(Context context, String ssid) {
        if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED ||
                ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_WIFI_STATE) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //请求权限
            return null;
        }

        List<WifiConfiguration> configs = wifiManager.getConfiguredNetworks();
        for (WifiConfiguration config : configs) {
            if (config.SSID.equals("\"" + ssid + "\"")) {
                return config;
            }
        }
        return null;
    }

    /**
     * 初始化公司wifi列表
     */
    private void initDefautlWifiList() {
        if (mWifiList == null) {
            mWifiList = new ArrayList<>();
        }
        if (mWifiList.size() < 3) {
            try {
                String[] ssidList = {
                        "Top-Notch-D1",
                        "Top-Notch-D2",
                        "Top-Notch-1",
                        "Top-Notch-2",
                        "Top-Notch-W"
                };
                String[] pwdList = {
                        "Topv5444",
                        "Topv5999",
                        "Topv5666",
                        "Topv5888",
                        "Topv587666"
                };

                for (int i = 0; i < ssidList.length; i++) {
                    ZHIWifiEntity w0 = new ZHIWifiEntity();
                    if (i >= pwdList.length) {
                        break;
                    }
                    w0.setName(ssidList[i]);
                    w0.setPassword(pwdList[i]);
                    w0.setState(0);

                    mWifiList.add(w0);
                }


            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 循环连接公司wifi
     */
    public int checkCompanyWifiConnectState(Context context, String ssid, String pwd) {
        try {
            wifiManager.disableNetwork(wifiManager.getConnectionInfo().getNetworkId());
            int netId = wifiManager.addNetwork(getWifiConfig(context, ssid, pwd, true));
            Log.d(TAG, "addNetwork: "+netId+" ssid:"+ssid);
            if (-1 == netId) {
//                if (listener != null) {
//                    listener.onCompanyWifiConnectFail(ssid);
//                }
                return -1;
            }

            boolean mConnectSuccess = wifiManager.enableNetwork(netId, true);
            Log.d(TAG, "mConnectSuccess: "+mConnectSuccess+" ssid:"+ssid);
            if (!mConnectSuccess) {
//                if (listener != null) {
//                    listener.onCompanyWifiConnectFail(ssid);
//                }
                return -1;
            }
//            if (listener != null) {
//                listener.onCompanyWifiConnectSuccess(ssid);
//            }
            return 1;
        } catch (Exception e) {
            e.printStackTrace();
//            if (listener != null) {
//                listener.onCompanyWifiNotFound(ssid);
//            }
            return -2;
        }
    }

//    /**
//     * 循环连接公司wifi
//     */
//    public void checkCompanyWifiConnectState(Context context, String ssid, String pwd, ZHIWifiConnectListener listener) {
//        try {
//            wifiManager.disableNetwork(wifiManager.getConnectionInfo().getNetworkId());
//            int netId = wifiManager.addNetwork(getWifiConfig(context, ssid, pwd, true));
//            if (-1 == netId) {
//                if (listener != null) {
//                    listener.onCompanyWifiConnectFail(ssid);
//                }
//                return;
//            }
//
//            boolean mConnectSuccess = wifiManager.enableNetwork(netId, true);
//            if (!mConnectSuccess) {
//                if (listener != null) {
//                    listener.onCompanyWifiConnectFail(ssid);
//                }
//                return;
//            }
//            if (listener != null) {
//                listener.onCompanyWifiConnectSuccess(ssid);
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//            if (listener != null) {
//                listener.onCompanyWifiNotFound(ssid);
//            }
//        }
//    }

//
//    /**
//     * 循环连接公司wifi
//     */
//    public void checkCompanyWifiConnectState(Context context, int index, ZHIWifiConnectListener listener) {
//        try {
//            if (mWifiList.size() > index) {
//                ZHIWifiEntity w0 = mWifiList.get(index);
//                String ssid = w0.getName();
//                String pwd = w0.getPassword();
//
//                wifiManager.disableNetwork(wifiManager.getConnectionInfo().getNetworkId());
//                int netId = wifiManager.addNetwork(getWifiConfig(context, ssid, pwd, true));
//                if (-1 == netId) {
//                    int gindex = (index + 1);
//                    checkCompanyWifiConnectState(context, gindex, listener);
//                    return;
//                }
//
//                boolean mConnectSuccess = wifiManager.enableNetwork(netId, true);
//                if (!mConnectSuccess) {
//                    int gindex = (index + 1);
//                    checkCompanyWifiConnectState(context, gindex, listener);
//                    return;
//                }
//                if (listener != null) {
//                    listener.onCompanyWifiConnectSuccess();
//                }
//            } else {
//                if (listener != null) {
//                    listener.onCompanyWifiNotFound();
//                }
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//            if (listener != null) {
//                listener.onCompanyWifiNotFound();
//            }
//        }
//    }

    public interface ZHIWifiConnectListener {
        void onCompanyWifiConnecting(String ssid);

        void onCompanyWifiConnectFail(String ssid);

        void onCompanyWifiConnectSuccess(String ssid);

        void onCompanyWifiNotFound(String ssid);
    }
}

